<?php

namespace TpAmis\Traits;

use TpAmis\Admin;
use TpAmis\Renderers\BaseApi;
use TpAmis\Support\Cores\AdminPipeline;
use TpAmis\Tools\File;

trait ElementTrait
{
    protected string $PrimaryKey = 'id';

    /**
     * 基础页面
     *
     * @return \TpAmis\Renderers\Page
     */
    protected function basePage()
    {
        return amis()->Page()->className('m:overflow-auto');
    }


    /**
     * Summary of DialogIframeButton
     * @param string $title
     * @param mixed $url
     * @param string $dialogSize * Dialog 大小 可选值: xs | sm | md | lg | xl | full
     * @param mixed $icon
     * @return \TpAmis\Renderers\DialogAction
     */
    public function DialogIframeButton(string $title = '', $url = 'form', string $dialogSize = 'full', $icon = '', $level  = 'primary')
    {
        $title = $title ?: '';

        $form   = amis()->IFrame()->src($url);
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($form)->size($dialogSize)->actions([])
        );

        $action->label($title)->level($level);
        if ($icon) {
            $action->icon(true);
        }
        if (! authAmis($action)) {
            return $action->disabled();
        }
        return $action;
    }

    public function DrawerButton(string $title = '', $formMonth = 'form', $url = 'form', string $dialogSize = 'md', $icon = '')
    {

        if (is_callable($formMonth)) {
            $form = call_user_func($formMonth);
        } else if (is_string($formMonth)) {
            $form = $this->$formMonth();
        } else {
            $form = $this->baseForm();
        }

        $form = $form->canAccessSuperData(false)->api(BaseApiPost($url))->onEvent([]);

        $action = amis()->DrawerAction()->drawer(
            amis()->Drawer()->title($title)->body($form)->size($dialogSize)
        );

        $action->label($title)->level('primary');
        if ($icon) {
            $action->icon(true);
        }
        if (! authAmis($action)) {
            return $action->disabled();
        }
        return $action;
    }

    public function DialogButton(string $title = '弹窗', $baseApi = '', string $dialogSize = 'md')
    {
        $urlPage = amis()->Service()->schemaApi($baseApi);
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($urlPage)->size($dialogSize)->actions([])
        );

        $action->label($title)->level('success');
        if (!authAmis($action)) {
            return $action->disabled();
        }
        return $action;
    }


    /**
     * 基础筛选器
     *
     * @return \TpAmis\Renderers\Form
     */
    protected function baseFilter()
    {
        $schema = amis()->Form()
            ->panelClassName('base-filter')
            ->title('')
            ->actions([
                amis()->Button()->label('重置')->actionType('clear-and-submit'),
                amis('submit')->label('搜索')->level('primary'),
            ]);

        return $schema;
    }

    /**
     * 基础筛选器 - 条件构造器
     *
     * @return \TpAmis\Renderers\ConditionBuilderControl
     */
    protected function baseFilterConditionBuilder()
    {
        return amis()->ConditionBuilderControl('filter_condition_builder');
    }

    protected $headerToolbar = [];

    public function setHeaderToolbar($headerToolbar)
    {
        $this->headerToolbar[] = $headerToolbar;
        return $this;
    }
    protected $bulkDeleteButton = [];

    public function setBulkDeleteButton($bulkDeleteButton)
    {
        $this->bulkDeleteButton[] = $bulkDeleteButton;
        return $this;
    }

    /**
     * @return \TpAmis\Renderers\CRUDTable
     */
    protected function baseCRUD()
    {

        $crud = amis()->CRUDTable()
            ->perPageField('list_rows')
            ->perPage(10)
            ->alwaysShowPagination()
            ->affixHeader(false)
            ->syncLocation(false)
            ->filterTogglable()
            ->filterDefaultVisible(false)
            ->api(BaseApiPost('index'))
            ->quickSaveApi(BaseApiPost('index', [['type' => 'quick']]))
            ->quickSaveItemApi(BaseApiPost('index', [['type' => 'quick_item']]))
            ->bulkActions(array_merge($this->bulkDeleteButton, [$this->bulkDeleteButton()]))
            ->perPageAvailable([10, 15, 20, 25, 50, 100])
            ->footerToolbar(['switch-per-page', 'statistics', 'pagination'])
            ->headerToolbar(array_merge($this->headerToolbar, $this->baseHeaderToolBar()));

        if (isset($this->service)) {
            $crud->set('primaryField', $this->getPrimaryKey());
        }

        return $crud;
    }



    /**
     * 获取主键
     * @return string
     */
    public function getPrimaryKey(): string
    {
        return $this->PrimaryKey;
    }

    /**
     * 获取主键
     * @param $PrimaryKey
     * @return string
     */
    public function setPrimaryKey($PrimaryKey): string
    {
        return $this->PrimaryKey = $PrimaryKey;
    }
    protected $ExportExcel = null;

    public function setTopExportExcel($label = '导出Excel', $api = null)
    {
        $this->ExportExcel = amis('export-excel')->align('right')->name($label);
        if ($api !== null) {
            $this->ExportExcel->api($api);
        }
    }

    protected $ExportCsv = null;
    public function setTopExportCsv($label = '导出CSV', $api = null)
    {
        $this->ExportCsv = amis('export-csv')->align('right')->name($label);
        if ($api !== null) {
            $this->ExportExcel->api($api);
        }
    }

    /**
     * 基础顶部工具栏
     *
     * @return array
     */
    protected function baseHeaderToolBar()
    {
        $schema[] = amis('bulkActions')->align('left');

        $schema[] = amis('reload')->align('right');

        $schema[] = amis('filter-toggler')->align('right');

        if ($this->ExportCsv == null) {
            $schema[] = amis('export-csv')->align('right');
        } else {
            $schema[] = $this->ExportCsv;
        }

        if ($this->ExportExcel) {
            $schema[] = amis('export-excel')->align('right');
        } else {
            $schema[] = $this->ExportExcel;
        }

        return $schema;
    }

    /**
     * 基础表单
     *
     * @param bool $back
     *
     * @return \TpAmis\Renderers\Form
     */
    protected function baseForm(bool $back = true)
    {

        $form = amis()->Form()->title(' ')->promptPageLeave();
        if ($back) {
            $form->onEvent([
                'submitSucc' => [
                    'actions' => [
                        ['actionType' => 'custom', 'script' => 'window.history.back()'],
                    ],
                ],
            ]);
        }
        return $form;
    }

    /**
     * @return \TpAmis\Renderers\Form
     */
    protected function baseDetail()
    {
        $schema = amis()->Form()
            ->panelClassName('px-48 m:px-0')
            ->title(' ')
            ->mode('horizontal')
            ->actions([])
            ->initApi(BaseApiPost('detail'));
        return $schema;
    }

    /**
     * 基础列表
     *
     * @param $crud
     *
     * @return \TpAmis\Renderers\Page
     */
    protected function baseList($crud)
    {
        return amis()->Page()->className('m:overflow-auto pb-48')->body($crud);
    }


    protected function FileManager()
    {
        return amis()->Page()->regions([
            '0' => 'body',
        ])->id('u:14e60c296775')->pullRefresh([
            'disabled' => '1',
        ])->body([
            amis()->Flex()->items([
                amis()->Container()->body([
                    amis()->TreeControl()->label('树组件')->name('tree')->options([
                        [
                            'label' => '选项A',
                            'value' => 'A',
                            'children' => [
                                [
                                    'label' => '选项C',
                                    'value' => 'C',
                                ],
                                [
                                    'label' => '选项D',
                                    'value' => 'D',
                                ],
                            ],
                        ],
                        [
                            'label' => '选项B',
                            'value' => 'B',
                        ],
                    ])->id('u:7dae8b587cad')->multiple('')->enableNodePath('')->hideRoot('1')->showIcon('1')->initiallyOpen('1'),
                ])->size('none')->style([
                    'position' => 'static',
                    'display' => 'block',
                    'flex' => '1 1 auto',
                    'flexGrow' => '1',
                    'flexBasis' => '0',
                ])->wrapperBody('')->isFixedHeight('')->isFixedWidth('')->id('u:20b299ad1577'),
                amis()->Container()->body([
                    amis()->ListControl()->label('列表')->name('list')->options([
                        [
                            'label' => '选项A',
                            'value' => 'A',
                        ],
                        [
                            'label' => '选项B',
                            'value' => 'B',
                        ],
                    ])->id('u:be6289ec2122'),
                ])->size('none')->style([
                    'position' => 'static',
                    'display' => 'block',
                    'flex' => '1 1 auto',
                    'flexGrow' => '3',
                    'flexBasis' => '0px',
                ])->wrapperBody('')->isFixedHeight('')->isFixedWidth('')->id('u:ead5482608c5'),
            ])->style([
                'position' => 'relative',
                'rowGap' => '10px',
                'columnGap' => '10px',
                'flexWrap' => 'nowrap',
                'inset' => 'auto',
            ])->id('u:beee00fc2f22')->isFixedHeight('')->isFixedWidth(''),
        ]);
    }
}
